<template>
	<view class="container">
		<!-- 状态栏（绿色） -->
		<view class="status-bar" :style="{ height: statusBarHeight + 'px' }"></view>
		
		<!-- 自定义导航栏（白色背景） -->
		<view class="custom-navbar" :style="{ paddingTop: statusBarHeight + 'px' }">
			<view class="navbar-content">
				<!-- 左侧返回箭头 -->
				<view class="navbar-left" @click="handleBack">
					<uni-icons type="left" size="20" color="#333333"></uni-icons>
				</view>
				<!-- 中间搜索输入框 -->
				<input 
					class="search-input" 
					type="text"
					placeholder="搜索账号"
					v-model="searchKeyword"
					@input="handleSearchInput"
					@confirm="handleSearchConfirm"
					:focus="isInputFocused"
				/>
				<!-- 清除按钮 -->
				<view 
					v-if="searchKeyword.trim() !== ''" 
					class="clear-button" 
					@click="handleClear"
				>
					<uni-icons type="closeempty" size="18" color="#999999"></uni-icons>
				</view>
			</view>
			<!-- 导航栏底部横线 -->
			<view class="navbar-divider"></view>
		</view>

		<!-- 主内容区 -->
		<view class="main-content" :style="{ marginTop: (statusBarHeight + 45) + 'px' }">
			<!-- 搜索结果列表 -->
			<scroll-view class="search-results" scroll-y v-if="searchKeyword.trim() !== ''">
				<view 
					class="result-item" 
					v-for="account in searchResults" 
					:key="account.id"
					@click="openAccountDetail(account)"
				>
					<view class="result-name">{{ account.name }}</view>
					<view class="result-account">账号: {{ account.account || account.subtitle || '' }}</view>
				</view>
				<view v-if="searchKeyword.trim() !== '' && searchResults.length === 0" class="no-results">
					未找到匹配的账号
				</view>
			</scroll-view>
			
			<!-- 未搜索时显示账号总数 -->
			<view v-else class="account-count">
				共有 {{ totalAccounts }} 个账号
			</view>
			
			<!-- 底部横条 -->
			<view class="home-indicator"></view>
		</view>
		
		<!-- 账号详情弹窗 -->
		<account-detail-modal 
			:visible="showAccountModal"
			:account-detail="selectedAccount"
			@close="closeAccountModal"
			@toggle-favorite="toggleFavorite"
			@edit="handleEditAccount"
		></account-detail-modal>
	</view>
</template>

<script>
	import { getAllAccounts, searchAccounts, toggleFavorite } from '@/utils/accountService.js';
	import AccountDetailModal from '@/components/Modal/account-detail-modal.vue';
	
	export default {
		components: {
			AccountDetailModal
		},
		data() {
			return {
				statusBarHeight: 0,
				searchKeyword: '',
				totalAccounts: 0,
				searchResults: [],
				isInputFocused: false,
				showAccountModal: false,
				selectedAccount: {},
				selectedAccountId: null
			}
		},
		onLoad(options) {
			// 获取状态栏高度
			const systemInfo = uni.getSystemInfoSync();
			this.statusBarHeight = systemInfo.statusBarHeight || 20;
			
			// 加载账号总数
			this.loadTotalAccounts();
			
			// 延迟聚焦输入框，确保页面渲染完成
			this.$nextTick(() => {
				setTimeout(() => {
					this.isInputFocused = true;
				}, 300);
			});
		},
		methods: {
			handleBack() {
				uni.navigateBack();
			},
			handleClear() {
				this.searchKeyword = '';
				this.searchResults = [];
			},
			handleSearchInput(e) {
				this.searchKeyword = e.detail.value;
				this.performSearch();
			},
			handleSearchConfirm(e) {
				this.searchKeyword = e.detail.value;
				this.performSearch();
			},
			performSearch() {
				if (this.searchKeyword.trim() === '') {
					this.searchResults = [];
					return;
				}
				this.searchResults = searchAccounts(this.searchKeyword);
			},
			loadTotalAccounts() {
				// 从存储中获取所有账号
				const accounts = getAllAccounts();
				this.totalAccounts = accounts.length;
			},
			openAccountDetail(account) {
				this.selectedAccountId = account.id;
				
				this.selectedAccount = {
					name: account.name || '',
					account: account.account || account.subtitle || '',
					password: account.password || '',
					note: account.note || '',
					isFavorite: account.isFavorite || false,
					tag: account.tag || '',
					lastModified: account.lastModified || new Date().toLocaleString('zh-CN', {
						year: 'numeric',
						month: '2-digit',
						day: '2-digit',
						hour: '2-digit',
						minute: '2-digit',
						second: '2-digit',
						hour12: false
					}).replace(/\//g, '-').replace(',', ''),
					customFields: account.customFields || {}
				};
				this.showAccountModal = true;
			},
			closeAccountModal() {
				this.showAccountModal = false;
				this.selectedAccountId = null;
			},
			toggleFavorite(isFavorite) {
				if (this.selectedAccountId) {
					try {
						const updatedAccount = toggleFavorite(this.selectedAccountId);
						if (updatedAccount) {
							this.selectedAccount.isFavorite = updatedAccount.isFavorite;
							// 重新搜索以更新列表
							this.performSearch();
						}
					} catch (error) {
						// uni.showToast({
						// 	title: error.message || '操作失败',
						// 	icon: 'none'
						// });
					}
				}
			},
			handleEditAccount() {
				if (!this.selectedAccountId) {
					// uni.showToast({
					// 	title: '无法获取账号ID',
					// 	icon: 'none'
					// });
					return;
				}
				
				// 关闭详情弹窗
				this.closeAccountModal();
				
				// 跳转到编辑页面
				uni.navigateTo({
					url: `/pages/add-account/add-account?accountId=${this.selectedAccountId}`,
					fail: (err) => {
						// uni.showToast({
						// 	title: '跳转失败',
						// 	icon: 'none',
						// 	duration: 2000
						// });
					}
				});
			}
		}
	}
</script>

<style lang="scss" scoped>
	.container {
		width: 100%;
		height: 100vh;
		background-color: #FFFFFF;
		display: flex;
		flex-direction: column;
	}

	// 状态栏（绿色）
	.status-bar {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		background-color: #008D57;
		z-index: 1001;
		width: 100%;
	}

	// 自定义导航栏（白色背景）
	.custom-navbar {
		background-color: #FFFFFF;
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		z-index: 1000;
		width: 100%;
	}

	.navbar-content {
		height: 44px;
		display: flex;
		align-items: center;
		padding: 0 24rpx;
		color: #333333;
		gap: 16rpx;
	}

	.navbar-divider {
		height: 0.5px;
		background-color: #F0F0F0;
		width: 100%;
	}

	.navbar-left {
		display: flex;
		align-items: center;
		justify-content: center;
		width: 40rpx;
		height: 40rpx;
		flex-shrink: 0;
	}

	.search-input {
		flex: 1;
		height: 44px;
		font-size: 28rpx;
		color: #333333;
		background-color: transparent;
		border: none;
		outline: none;
		margin-left: 16rpx;
		
		&::placeholder {
			color: #999999;
		}
	}

	.clear-button {
		display: flex;
		align-items: center;
		justify-content: center;
		width: 32rpx;
		height: 32rpx;
		margin-left: 8rpx;
		flex-shrink: 0;
		cursor: pointer;
		
		&:active {
			opacity: 0.7;
		}
	}

	// 主内容区
	.main-content {
		flex: 1;
		width: 100%;
		background-color: #FFFFFF;
		display: flex;
		flex-direction: column;
		box-sizing: border-box;
		position: relative;
	}

	.search-results {
		flex: 1;
		width: 100%;
		padding: 0;
	}

	.result-item {
		padding: 32rpx;
		border-bottom: 1rpx solid #F5F5F5;
		cursor: pointer;
		
		&:active {
			background-color: #F8F8F8;
		}
	}

	.result-name {
		font-size: 30rpx;
		color: #008D57;
		margin-bottom: 8rpx;
		font-weight: 500;
	}

	.result-account {
		font-size: 28rpx;
		color: #999999;
	}

	.no-results {
		padding: 60rpx 32rpx;
		text-align: center;
		font-size: 28rpx;
		color: #999999;
	}

	.account-count {
		flex: 1;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 28rpx;
		color: #666666;
		text-align: center;
		line-height: 1.5;
	}

	.home-indicator {
		position: fixed;
		bottom: 0;
		left: 50%;
		transform: translateX(-50%);
		width: 80rpx;
		height: 4rpx;
		background-color: #CCCCCC;
		border-radius: 2rpx;
		margin-bottom: 20rpx;
	}
</style>

